from datetime import datetime
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA256
from urllib.parse import quote_plus
from urllib.parse import urlparse, parse_qs
from base64 import decodebytes, encodebytes
import json
import requests
import asyncio

alipay_public_key_path = '../keys/alipay_public'    # 公钥
app_private_key_path = '../keys/app_private'    # 应用私钥
appid = '2021000119635001'      # 应用appid
app_notify_url = 'http://127.0.0.1:9999/school/school'  # 默认回调url,
return_url = 'http://localhost:8080/school/school'
sign_type = 'RSA2'         # 签名类型
debug = True         # 调试环境



class AliPay:
    """
    支付宝支付接口(PC端支付接口)
    """

    def __init__(self, appid, app_notify_url, app_private_key_path,
                 alipay_public_key_path, return_url, debug=True):
        self.appid = appid
        self.app_notify_url = app_notify_url
        self.app_private_key_path = app_private_key_path
        self.app_private_key = None
        self.return_url = return_url
        with open(self.app_private_key_path) as fp:
            self.app_private_key = RSA.importKey(fp.read())

        self.alipay_public_key_path = alipay_public_key_path
        with open(self.alipay_public_key_path) as fp:
            self.alipay_public_key = RSA.importKey(fp.read())

        if debug is True:
            self.__gateway = "https://openapi.alipaydev.com/gateway.do"
        else:
            self.__gateway = "https://openapi.alipay.com/gateway.do"

    def direct_pay(self, subject, out_trade_no, total_amount, return_url=None, **kwargs):
        biz_content = {
            "subject": subject,
            "out_trade_no": out_trade_no,
            "total_amount": total_amount,
            "product_code": "FAST_INSTANT_TRADE_PAY",
            # "qr_pay_mode":4
        }
        biz_content.update(kwargs)
        data = self.build_body("alipay.trade.page.pay", biz_content, self.return_url)
        str = self.sign_data(data)
        return self.__gateway + '?' + str

    # 转账
    def transfer(self,out_biz_no,trans_amount,identity):

        biz_content = {
            'out_biz_no':out_biz_no,
            'trans_amount': trans_amount,
            'product_code':'TRANS_ACCOUNT_NO_PWD',
            'biz_scene':'DIRECT_TRANSFER',
            'order_title':'提现',
            'payee_info':{
                'identity':identity,
                'identity_type':'ALIPAY_USER_ID',
            }
        }
        data = self.build_body("alipay.fund.trans.uni.transfer", biz_content)
        url = self.__gateway + "?" + self.sign_data(data)
        print(url)
        # res = httpclient.AsyncHTTPClient().fetch(url, method='GET', validate_cert=False, connect_timeout=30.0,
        #                                                request_timeout=30.0)
        res = requests.get(url=url)
        print('转账',res)
        # return json.loads(res.body.decode())
    # 转账状态
    def transfer_type(self,out_biz_no):
        biz_content = {
            'out_biz_no': out_biz_no,
            'product_code': 'TRANS_ACCOUNT_NO_PWD',
            'biz_scene': 'DIRECT_TRANSFER',
        }
        data = self.build_body("alipay.fund.trans.common.query", biz_content)
        url = self.__gateway + "?" + self.sign_data(data)
        print(url)
        # res = httpclient.AsyncHTTPClient().fetch(url, method='GET', validate_cert=False, connect_timeout=30.0,
        #                                                request_timeout=30.0)
        res = requests.get(url=url)
        print('转账状态',res)
        # return json.loads(res.body.decode())

    # 查询订单状态方法
    def api_alipay_trade_query(self,out_trade_no=None,**kwargs):
            biz_content = {
                "out_trade_no": out_trade_no
            }
            biz_content.update(**kwargs)

            data = self.build_body("alipay.trade.query", biz_content)
            url = self.__gateway + "?" + self.sign_data(data)
            res = requests.get(url=url)
            print('收到的响应',res.content)


    #请求支付宝退款接口
    def api_alipay_trade_refund(self, refund_amount, out_trade_no=None, trade_no=None, **kwargs):
            biz_content = {
                "refund_amount": refund_amount
            }
            biz_content.update(**kwargs)
            if out_trade_no:
                biz_content["out_trade_no"] = out_trade_no
            if trade_no:
                biz_content["trade_no"] = trade_no
            data =self.build_body("alipay.trade.refund", biz_content)
            url = self.__gateway + "?" + self.sign_data(data)
            # res = httpclient.AsyncHTTPClient().fetch(url,method='GET',validate_cert=False,connect_timeout=30.0, request_timeout=30.0)
            res = requests.get(url=url)
            print(res,'请求支付宝退款接口')


    def build_body(self, method, biz_content, return_url=None):
        data = {
            "app_id": self.appid,
            "method": method,
            "charset": "utf-8",
            "sign_type": "RSA2",
            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "version": "1.0",
            "biz_content": biz_content
        }

        if return_url is not None:
            data["notify_url"] = self.app_notify_url
            data["return_url"] = self.return_url

        return data

    def sign_data(self, data):
        data.pop("sign", None)
        # 排序后的字符串
        unsigned_items = self.ordered_data(data)
        # print(unsigned_items)
        unsigned_string = "&".join("{0}={1}".format(k, v) for k, v in unsigned_items)
        sign = self.sign(unsigned_string.encode("utf-8"))
        # ordered_items = self.ordered_data(data)
        quoted_string = "&".join("{0}={1}".format(k, quote_plus(v)) for k, v in unsigned_items)

        # 获得最终的订单信息字符串
        signed_string = quoted_string + "&sign=" + quote_plus(sign)
        return signed_string

    def ordered_data(self, data):
        complex_keys = []
        for key, value in data.items():
            if isinstance(value, dict):
                complex_keys.append(key)

        # 将字典类型的数据dump出来
        for key in complex_keys:
            data[key] = json.dumps(data[key], separators=(',', ':'))

        return sorted([(k, v) for k, v in data.items()])

    def sign(self, unsigned_string):
        # 开始计算签名
        key = self.app_private_key
        signer = PKCS1_v1_5.new(key)
        signature = signer.sign(SHA256.new(unsigned_string))
        # base64 编码，转换为unicode表示并移除回车
        sign = encodebytes(signature).decode("utf8").replace("\n", "")
        return sign

    def _verify(self, raw_content, signature):
        # 开始计算签名
        key = self.alipay_public_key
        signer = PKCS1_v1_5.new(key)
        digest = SHA256.new()
        digest.update(raw_content.encode("utf8"))
        if signer.verify(digest, decodebytes(signature.encode("utf8"))):
            return True
        return False

    def verify(self, data, signature):
        if "sign_type" in data:
            sign_type = data.pop("sign_type")
        # 排序后的字符串
        unsigned_items = self.ordered_data(data)
        message = "&".join(u"{}={}".format(k, v) for k, v in unsigned_items)
        return self._verify(message, signature)



ali = AliPay(appid=appid,alipay_public_key_path=alipay_public_key_path,
             app_notify_url=app_notify_url,app_private_key_path=app_private_key_path,
             return_url=return_url)

# print(ali.direct_pay('zhifu','20230512',944))    #获取支付地址   支付标题   订单号   金额
# print(ali.transfer('20230519',944,2088622958044653))   #转账    订单号   金额   转账收款方用户uid
# print(ali.api_alipay_trade_refund(944,'20230512'))     #退款    金额   订单号
# print(ali.api_alipay_trade_query('20230512'))     #查询支付状态 订单号